/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Form, Input, Divider } from 'antd';
import { connect } from 'dva';
import KbModal from '@/components/KbModal';
import KbIcon from '@/components/KbIcon';
import KbChildrenWrapper from '@/components/KbChildrenWrapper';
import patterns, { check } from '@/utils/patterns';
import styles from './index.less';

const { Item: FormItem } = Form;

@connect(({ loading }) => ({
  submitting: loading.effects['source/getKopBrand'],
  matching: loading.effects['courier/matchCourier'],
}))
@Form.create()
class Agree extends Component {
  static defaultProps = {
    action: 'add',
    onAdded: () => {},
  };

  constructor(props) {
    super(props);
    this.state = {
      isKdy: false,
      visible: false,
    };
    this.actionConfig = {
      add: {
        tips: [
          <>
            获取快递员授权单号源，您的签约快递员必须是
            <a href="//www.kuaidihelp.com/app/kdy" target="_blank">
              快递员APP
            </a>
            用户
          </>,
          '获取快递员单号授权，需要快递员在快递员APP上操作同意，请事先与快递员协商一致。',
          <>
            授权单号源如涉及费用结算，请与快递员线下确认交付
            <br />
            <a href="//m.kuaidihelp.com/help/wzg_help_0" target="_blank">
              了解更多&gt;&gt;
            </a>
          </>,
        ],
        title: '添加签约快递员',
      },
      sign: {
        tips: [
          <>
            1、必须是
            <a href="//www.kuaidihelp.com/app/kdy" target="_blank">
              快递员APP
            </a>
            用户才可签约并同步订单
          </>,
          <>
            2、如需使用快递员的单号源，请让快递员在【快递员APP-&gt;客户管理-&gt;微商客户】里进行设置
            <Divider type="vertical" />
            <a href="//m.kuaidihelp.com/help/wzg_help_0" target="_blank">
              点击查看更多帮助&gt;&gt;
            </a>
          </>,
        ],
        title: '添加签约快递员',
      },
    };
  }

  //   打开或关闭指定弹窗
  onTriggerModal = open => {
    this.setState({
      visible: open,
    });
  };

  // 提交
  onOk = () => {
    const { form, dispatch, onAdded } = this.props;
    form.validateFields({ first: true }, (err, values) => {
      if (err) return;
      dispatch({
        type: 'courier/signCourier',
        payload: values,
      }).then(res => {
        if (res.code == 0) {
          this.setState(
            {
              isKdy: false,
              errMessage: '',
            },
            () => {
              this.onTriggerModal(false);
              form.resetFields();
              onAdded();
              dispatch({
                type: 'source/getAgree',
              });
            }
          );
        }
      });
    });
  };

  // 输入快递员手机号
  onInputChange = e => {
    const { value: courierMobile } = e.target;
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      const res = check('phone', courierMobile);
      if (res.code === 0) {
        // 手机号
        const { dispatch } = this.props;
        dispatch({
          type: 'courier/matchCourier',
          payload: {
            courierMobile,
          },
        }).then(res => {
          const { code, data, msg } = res;
          if (code == 0 && data && data.username) {
            this.setState({
              errMessage: '',
              isKdy: true,
            });
          } else {
            this.setState({
              isKdy: false,
              errMessage: msg,
            });
          }
        });
      } else {
        this.setState({
          isKdy: false,
          errMessage: ''
        });
      }
    }, 500);
  };

  render() {
    const { visible, errMessage, isKdy } = this.state;
    const { children, form, submitting, matching, action,action_ } = this.props;
    const { title, tips } = this.actionConfig[action];
    return (
      <>
        <KbChildrenWrapper className="pointer" onClick={this.onTriggerModal.bind(this, true)}>
          {children}
        </KbChildrenWrapper>
        <KbModal
          loading={!!matching}
          visible={visible}
          onCancel={this.onTriggerModal.bind(this, false)}
          title={title}
          okText="提交"
          onOk={this.onOk}
          okButtonProps={{ loading: submitting, disabled: matching || !isKdy }}
          footer={
            <div className="kb-tips">
              <div className="kb-tips_title">温馨提示：</div>
              {tips.map((item, index) => (
                <div key={index} className="kb-tips_item">
                  {item}
                </div>
              ))}
            </div>
          }
        >
          <Form>
            <FormItem help="" style={{ marginBottom: 12 }}>
              {form.getFieldDecorator('courierMobile', {
                rules: [
                  {
                    required: true,
                    message: '请输入快递员手机号',
                  },
                  {
                    ...patterns.phone,
                  }
                ]
              })(
                <Input
                  size="large"
                  maxLength={11}
                  onChange={this.onInputChange}
                  prefix={<KbIcon style={{ color: '#999' }} type="mobile" />}
                  placeholder="请输入快递员手机号"
                />
              )}
            </FormItem>
            {action_ !== 'sign' && (
              <FormItem
                style={{ marginBottom: 12 }}
                help={
                  <>
                    <KbIcon style={{ color: 'red', marginRight: 8 }} type="exclamation-circle" />
                    添加后，需快递员在【快递员APP→客户管理→微商客户】内进行授权单号源的设置，才可使用
                  </>
                }
              ></FormItem>
            )}
          </Form>
          <div className={styles.error}> {errMessage}</div>
        </KbModal>
      </>
    );
  }
}

export default Agree;
